package com.zyx;

import com.zyx.netty.server.BusiControlServer;
import com.zyx.netty.server.DeviceControlServer;
import io.netty.channel.ChannelFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application implements CommandLineRunner {
	private static final Logger logger = LoggerFactory.getLogger(Application.class);

	@Value("${netty.business.port}")
	private int busiPort;
	@Value("${netty.device.port}")
	private int devicePort;

	@Autowired
	DeviceControlServer deviceControlServer;
	@Autowired
	BusiControlServer busiControlServcer;

	public static void main(String[] args) {

		SpringApplication.run(Application.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		final ChannelFuture[] futures = new ChannelFuture[2];

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					futures[0] = deviceControlServer.start(devicePort);
					if(futures[0].isSuccess()){
						logger.info("***********对接设备端服务启动成功，port:{}**********",devicePort);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					futures[1] = busiControlServcer.start(busiPort);
					if(futures[1].isSuccess()){
						logger.info("***********对接业务端服务启动成功，port:{}***********",busiPort);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();

		Runtime.getRuntime().addShutdownHook(new Thread(){
			@Override
			public void run() {
				busiControlServcer.destroy();
				deviceControlServer.destroy();
			}
		});
		//服务端管道关闭的监听器并同步阻塞,直到channel关闭,线程才会往下执行,结束进程
		for(ChannelFuture f:futures){
//			f.channel().closeFuture().syncUninterruptibly();
		}

	}
}
